package com.yjb.tenet.boot.framework.satoken.core.filter;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.stp.StpUtil;
import com.yjb.tenet.boot.common.exception.enums.ErrorCodeEnum;
import com.yjb.tenet.boot.common.pojo.ResponseResult;
import com.yjb.tenet.boot.framework.satoken.core.init.PermitAllUrlInitializingBean;
import org.springframework.http.HttpStatus;

/**
 * @description 
 * @author yinjinbiao
 * @create 2023/3/1 12:00
 * @version 1.0
 */
public class LoginUserWebFilter extends SaServletFilter {

	public LoginUserWebFilter(PermitAllUrlInitializingBean permitAllUrlInitializingBean) {
		super.addInclude("/**")
				// knife4j , swagger 静态资源
				.addExclude("/webjars/**","/doc.html","/swagger-resources/**","/v2/api-docs/**", "/v3/api-docs/**");
		permitAllUrlInitializingBean.getUrls().forEach(url->super.addExclude(url));
		super
				.setAuth(obj -> {
					// 获取 LoginUser
					StpUtil.checkLogin();
				})
				.setError(e -> {
					SaHolder.getResponse().setHeader("Content-Type", "application/json;charset=UTF-8");
					SaHolder.getResponse().setStatus(HttpStatus.UNAUTHORIZED.value());
					return ResponseResult.error(ErrorCodeEnum.UNAUTHORIZED.getCode(), "未登录或登录状态失效！");
				});
	}
}
